"""FastAPI应用入口文件"""

from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn

from app.core.config import settings
from app.api.v1.api import api_router
from app.utils.logger import get_logger
from app.utils.exceptions import TextDetectionException

# 创建日志记录器
logger = get_logger("main")

# 创建FastAPI应用实例
app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    description="基于FastAPI的文本语言检测API服务，支持知网、格子达、维普等多个检测平台",
    openapi_url=f"{settings.api_v1_str}/openapi.json" if settings.debug else None,
    docs_url="/docs" if settings.debug else None,
    redoc_url="/redoc" if settings.debug else None,
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.allowed_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.middleware("http")
async def logging_middleware(request: Request, call_next):
    """请求日志中间件"""
    start_time = __import__('time').time()
    
    # 记录请求信息
    logger.info(f"收到请求: {request.method} {request.url}")
    
    # 处理请求
    response = await call_next(request)
    
    # 计算处理时间
    process_time = __import__('time').time() - start_time
    
    # 记录响应信息
    logger.info(f"请求完成: {request.method} {request.url} - 状态码: {response.status_code} - 耗时: {process_time:.3f}s")
    
    return response


@app.exception_handler(TextDetectionException)
async def text_detection_exception_handler(request: Request, exc: TextDetectionException):
    """文本检测异常处理器"""
    logger.error(f"文本检测异常: {exc.message}")
    return JSONResponse(
        status_code=400,
        content={
            "success": False,
            "error_code": exc.error_code,
            "message": exc.message,
            "timestamp": __import__('datetime').datetime.now().isoformat()
        }
    )


@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    """HTTP异常处理器"""
    logger.error(f"HTTP异常: {exc.status_code} - {exc.detail}")
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "success": False,
            "error_code": f"HTTP_{exc.status_code}",
            "message": exc.detail,
            "timestamp": __import__('datetime').datetime.now().isoformat()
        }
    )


@app.exception_handler(500)
async def internal_server_error_handler(request: Request, exc: Exception):
    """服务器内部错误处理器"""
    logger.error(f"服务器内部错误: {str(exc)}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={
            "success": False,
            "error_code": "INTERNAL_SERVER_ERROR",
            "message": "服务器内部错误",
            "timestamp": __import__('datetime').datetime.now().isoformat()
        }
    )


# 包含API路由
app.include_router(api_router)


@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    logger.info("=" * 50)
    logger.info(f"🚀 {settings.app_name} v{settings.app_version} 正在启动...")
    logger.info(f"📝 调试模式: {'开启' if settings.debug else '关闭'}")
    logger.info(f"🌐 API文档: http://localhost:8000/docs" if settings.debug else "生产环境，API文档已禁用")
    logger.info("=" * 50)


@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭事件"""
    logger.info("🛑 应用正在关闭...")
    # 这里可以添加清理逻辑，如关闭数据库连接等


@app.get("/", tags=["根路径"])
async def root():
    """根路径"""
    return {
        "message": f"欢迎使用 {settings.app_name}",
        "version": settings.app_version,
        "docs_url": "/docs" if settings.debug else "文档在生产环境中不可用",
        "health_check": "/health"
    }


if __name__ == "__main__":
    # 运行应用
    uvicorn.run(
        "app.main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.debug,
        log_level=settings.log_level.lower()
    ) 